<template>
  <drawer :show="props.show" :title="'找人代取'" @close="close" :show-close="true">
    <view class="cs_main">
      <view class="times">
        <view>代取链接有效期</view>
        <view>24小时 ＞</view>
      </view>
      <view class="tips">
        <view class="title">温馨提示：</view>
        <view class="content">
          为了您的货物安全，代取链接的有效期默认为24小时，请嘱咐代取人在有效期内点击链接，逾期链接将失效。
        </view>
      </view>
    </view>
    <view class="ways">
      <view class="title">发送方式</view>
      <view class="content">
        <button open-type="share" class="shareBtn">
          <view class="block">
            <image src="../../assets/images/index/way1.png"></image>
            <text>微信</text>
          </view>
        </button>
        <view class="block" @click="shareSms">
          <image src="../../assets/images/index/way2.png"></image>
          <text>短信</text>
        </view>
        <view class="block" @click="shareQr">
          <image src="../../assets/images/index/way3.png"></image>
          <text>二维码</text>
        </view>
      </view>
    </view>
    <nut-overlay v-model:visible="showSms" :close-on-click-overlay="false">
      <view class="wrapper_sms">
        <view class="heads"></view>
        <view class="formtitle">请输入对方手机号码</view>
        <view>
          <nut-input
              v-model="smsFormData.tel"
              placeholder="请填写对方手机号码"
              :border="false"
          />
        </view>
        <view class="foots">
          <view class="left_btn" @click="showSms=false">取消</view>
          <view class="right_btn" @click="submitSms">确定</view>
        </view>
      </view>
    </nut-overlay>
  </drawer>
  <drawer :show="showQr" :title="'二维码分享图'" @close="closeQr" :show-close="true" :z-index="21">
    <view style="width:100%;background-color:#f5f5f5;">
      <view class="qrs">
        <view class="title_qr">
          <image class="img" mode="scaleToFill" src="../../assets/images/sign/logo.png"></image>
          <view class="right">
            <image class="phone" mode="scaleToFill" src="../../assets/images/sign/phone.png"></image>
            <text class="text">客服热线：952999</text>
          </view>
        </view>
        <view class="bill_body">
          <view class="layers f2">
            <view>
              <image class="img" mode="scaleToFill" src="../../assets/images/sign/fa.png"></image>
              <view class="address">
                <text class="name">{{ order.orderList.shipper }} {{ order.orderList.shipperMobile }}</text>
                <text class="addr">{{ order.orderList.toFromAdd }}</text>
              </view>
            </view>
            <view>
              <image class="img" mode="scaleToFill" src="../../assets/images/sign/shou.png"></image>
              <view class="address">
                <text class="name">{{ order.orderList.receiver }} {{ order.orderList.receiverMobile }}</text>
                <text class="addr">{{ order.orderList.fromAdd }}</text>
              </view>
            </view>
          </view>
          <view class="layers f3" v-for="(item,index) in order.orderList.goodsInfo">
            <view class="row">
              <view class="width_100">
                <text class="label">货物名称：</text>
                <text class="value">{{ item.goodsName }}</text>
              </view>
            </view>
            <view class="row">
              <view class="width_100">
                <text class="label">规格：</text>
                <text class="value">{{ item.specifications }}</text>
              </view>
            </view>
            <view class="row">
              <view class="width_50">
                <text class="label">件数：</text>
                <text class="value">{{ item.goodsNumber }}件</text>
              </view>
              <view class="width_50">
                <text class="label">包装：</text>
                <text class="value">{{ item.packing }}</text>
              </view>
            </view>
            <view class="row">
              <view class="width_50">
                <text class="label">重量：</text>
                <text class="value">{{ item.weigh }}kg</text>
              </view>
              <view class="width_50">
                <text class="label">体积：</text>
                <text class="value">{{ item.goodsVolume }}m³</text>
              </view>
            </view>
          </view>
          <view class="layers qr">
            <image class="img1" src="../../assets/images/index/fingerprint.png" mode="scaleToFill"></image>
            <view class="text">我有货物需要你帮忙代取,长按识别二维码帮我代取吧~</view>
            <view>
              <image class="img2" :src="'data:image/png;base64,'+qrCodeUrl" mode="scaleToFill" ref="qrImg"></image>
            </view>
          </view>
        </view>
      </view>
      <view class="qrfoot">
        <view class="btn" @click="previewQrCode">保存到相册</view>
      </view>
    </view>
  </drawer>


  <view style="position:fixed;left:0;top:99999999rpx">
    <canvas style="width: 500rpx;height: 400rpx;" canvas-id="wxfx"></canvas>
    <canvas style="width: 351px;height: 1000px;" canvas-id="qrcodes"></canvas>
  </view>
  <image src="../../assets/images/index/sharewx.png" v-if="false"></image>
  <image src="../../assets/images/index/sharewx1.png" v-if="false"></image>
  <image src="../../assets/images/index/shareqr/qrhead.png" v-if="false"></image>

</template>

<script lang="ts" setup>
import drawer from '@/components/drawer'
import Taro, {getCurrentInstance, useShareAppMessage} from '@tarojs/taro'
import { $post } from '@/@api'
import { ref, watch } from "vue"
import useMyOrderStore from "@/store/myOrder"
import dayjs from "dayjs"
const { page } = getCurrentInstance()

const props = defineProps<{
  show: boolean
  type: string
}>()
const emit = defineEmits<{
  (e: 'close')
}>()
const order = useMyOrderStore()
const shareData = ref<object>({
  title: '我有货物需要你帮忙代取，点击盛辉小程序链接，帮我代取吧~',
  imageUrl: '',
  path: '/pages/receiveAgent/index'
})
const showSms = ref<boolean>(false)
const showQr = ref<boolean>(false)
const qrCodeUrl = ref<string>(false)
const smsFormData = ref<any>({
  name: '',
  tel: ''
})


const close = ()=>{
  emit('close')
}
const closeQr = () => {
  showQr.value = false
}

const shareWx = ()=>{

}

//半角转全角
const ToDBC = (txtstring) => {
  var tmp = "";
  for(var i=0;i<txtstring.length;i++){
    if(txtstring.charCodeAt(i)==32){
      tmp += String.fromCharCode(12288)
    }
    else if(txtstring.charCodeAt(i)<127){
      tmp += String.fromCharCode(txtstring.charCodeAt(i)+65248)
    }
    else {
      tmp += txtstring[i]
    }
  }
  return tmp
}

//短信方式
const shareSms = ()=>{
  showSms.value = true
}
const submitSms = async ()=>{
  if(!smsFormData.value.tel){
    Taro.showToast({
      icon: 'none',
      title: '请填写手机号'
    })
    return
  }
  const res = await $post('/selfmachine-system/order/getLinkByCode', {
    name: smsFormData.value.name,
    tel: smsFormData.value.tel,
    hours: 24,
    billNo: order.orderList.billNo,
    type: 'sms'
  })
  if(res.data.code == 200){
    Taro.showToast({
      icon: 'none',
      title: '发送短信成功'
    })
    showSms.value = false
  }
  else{
    Taro.showToast({
      icon: 'error',
      title: '发送短信失败'
    })
  }
}

//二维码方式
const shareQr = async ()=>{
  const res = await $post('/selfmachine-system/order/getLinkByCode', {
    hours: 24,
    billNo: order.orderList.billNo,
    type: 'qrCode'
  })
  if(res.data.code == 200){
    qrCodeUrl.value = res.data.data.qrCode
    showQr.value = true
  }
}

const previewQrCode = ()=>{
  const ctx = Taro.createCanvasContext('qrcodes')

  const Rect = function(x, y, w, h) {
    return {x:x, y:y, width:w, height:h}
  }
  const Point = function(x, y) {
    return {x:x, y:y}
  }

  function drawRoundedRect(rect, r) {
    var ptA = Point(rect.x + r, rect.y)
    var ptB = Point(rect.x + rect.width, rect.y)
    var ptC = Point(rect.x + rect.width, rect.y + rect.height)
    var ptD = Point(rect.x, rect.y + rect.height)
    var ptE = Point(rect.x, rect.y)

    ctx.beginPath()
    ctx.moveTo(ptA.x, ptA.y)
    ctx.arcTo(ptB.x, ptB.y, ptC.x, ptC.y, r)
    ctx.arcTo(ptC.x, ptC.y, ptD.x, ptD.y, r)
    ctx.arcTo(ptD.x, ptD.y, ptE.x, ptE.y, r)
    ctx.arcTo(ptE.x, ptE.y, ptA.x, ptA.y, r)
    ctx.closePath()
    ctx.stroke()
  }

  const ctxObj = {
    ...order.orderList,
    shipperAddress: (order.orderList.toProvince + order.orderList.toFromCity +order.orderList.toFromArea + order.orderList.toFromAdd) || '-',
    receiverAddress: (order.orderList.fromProvince + order.orderList.fromCity +order.orderList.fromArea + order.orderList.fromAdd) || '-',
    goodsInfo: order.orderList.goodsInfo || [],
  }

  ctx.fillStyle = '#fff'
  ctx.fillRect(0,0,351, 1000)

  ctx.drawImage('../../assets/images/index/shareqr/qrhead.png', 0, 0, 351, 56)

  ctx.strokeStyle = '#e3e7ec'
  ctx.lineWidth = 1
  // drawRoundedRect(Rect(8, 64, 335, 112), 12)
  ctx.strokeRect(8, 64, 335, 112)

  ctx.beginPath()
  ctx.arc(30,94,10,0, 2*Math.PI )
  ctx.fillStyle = '#0966ff'
  ctx.fill()
  ctx.closePath()

  ctx.beginPath()
  ctx.arc(30,144,10,0, 2*Math.PI )
  ctx.fillStyle = '#0ec767'
  ctx.fill()
  ctx.closePath()

  ctx.beginPath()
  ctx.fillStyle = '#fff'
  ctx.font = "10px 黑体"
  ctx.fillText('发', 25, 98 )
  ctx.fillText('收', 25, 148 )
  ctx.closePath()

  ctx.fillStyle = '#252525'
  ctx.font = "13px 黑体"
  ctx.fillText(`${ctxObj.shipper}  ${ctxObj.shipperMobile||'-'}`, 48, 90, 280)
  ctx.fillText(`${ctxObj.receiver}  ${ctxObj.receiverMobile||'-'}`, 48, 140, 280)

  ctx.fillStyle = '#999'
  ctx.font = "11px 黑体"
  ctx.fillText(ctxObj.shipperAddress, 48, 110, 280)
  ctx.fillText(ctxObj.receiverAddress, 48, 160, 280)

  //货物信息
  for(let i=0; i<ctxObj.goodsInfo.length; i++) {
    ctx.strokeStyle = '#e3e7ec'
    ctx.strokeRect(8, 176 + 104*i, 335, 104)
    //货物信息label
    ctx.beginPath()
    ctx.fillStyle = '#999'
    ctx.font = "11px 黑体"
    ctx.fillText('货物名称：', 20, 199 + 104*i)
    ctx.fillText('规格：', 20, 221 + 104*i)
    ctx.fillText('件数：', 20, 243 + 104*i)
    ctx.fillText('包装：', 187, 243 + 104*i)
    ctx.fillText('重量：', 20, 265 + 104*i)
    ctx.fillText('体积：', 187, 265 + 104*i)
    ctx.closePath()
    //货物信息value
    ctx.beginPath()
    ctx.fillStyle = '#252525'
    ctx.font = "11px 黑体"
    ctx.fillText(ctxObj.goodsInfo[i].goodsName, 96, 199 + 104*i, 230)
    ctx.fillText(ctxObj.goodsInfo[i].specifications, 96, 221 + 104*i, 230)
    ctx.fillText(`${ctxObj.goodsInfo[i].goodsNumber}件`, 96, 243 + 104*i, 90)
    ctx.fillText(ctxObj.goodsInfo[i].packing, 263, 243 + 104*i, 70)
    ctx.fillText(`${ctxObj.goodsInfo[i].weigh}kg`, 96, 265 + 104*i, 90)
    ctx.fillText(`${ctxObj.goodsInfo[i].goodsVolume}m³`, 263, 265 + 104*i, 70)
    ctx.closePath()
  }

  //二维码行
  ctx.strokeStyle = '#e3e7ec'
  ctx.strokeRect(8, 176 + 104*ctxObj.goodsInfo.length, 335, 96)
  ctx.drawImage('../../assets/images/index/fingerprint.png', 20, 206 + 104*ctxObj.goodsInfo.length, 36, 36)
  ctx.fillStyle = '#252525'
  ctx.font = "bold 14px 黑体"
  ctx.fillText('我有货物需要你帮忙代取', 64, 216 + 104*ctxObj.goodsInfo.length)
  ctx.fillText('长按识别二维码帮我代取吧~', 64, 240 + 104*ctxObj.goodsInfo.length)
  //二维码转图片
  let code = qrCodeUrl.value
  const fsm = Taro.getFileSystemManager()
  code = code.replace(/\ +/g, "")
  code = code.replace(/[\r\n]/g, "")
  const buffer = Taro.base64ToArrayBuffer(code)
  const filePath = Taro.env.USER_DATA_PATH + '/shwxqrcode'+new Date().getTime()+'.png'
  fsm.writeFileSync(filePath, buffer, 'binary')
  ctx.drawImage(filePath, 259, 188 + 104*ctxObj.goodsInfo.length, 72, 72)

  ctx.draw()

  Taro.canvasToTempFilePath({
    canvasId: 'qrcodes',
    height: 280 + 104*ctxObj.goodsInfo.length,
    success: (res)=>{
      console.log(res.tempFilePath)
      Taro.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: res => {
          Taro.showToast({
            title: '成功保存到相册',
            icon: 'success'
          })
          showQr.value = false
        }
      })
    }
  })
}

//微信分享绘制海报
const drawWxShare = (resolve?:object)=> {
  let ctxObj = {
    destinationBranchName: order.orderList.destinationBranchName || '',
    destinationBranchNameLength: (order.orderList.destinationBranchName || '').length,
    shipper: ToDBC(order.orderList.shipper || ''),
    shipperLength: (order.orderList.shipper || '').length,
    receiver: ToDBC(order.orderList.receiver || ''),
    receiverLength: (order.orderList.receiver || '').length,
    destinationAddress: order.orderList.destinationAddress || ''
  }
  //画布画笔
  const ctx = Taro.createCanvasContext('wxfx')
  //背景图
  ctx.drawImage('../../assets/images/index/sharewx.png', 0, 0, 250, 200)
  //发货人取货人
  ctx.fillStyle = '#fff'
  ctx.font = "14px 黑体"
  ctx.fillText(ctxObj.shipper, 6+(86-ctxObj.shipperLength*14)/2, 90, 86)
  ctx.fillText(ctxObj.receiver, 158+(86-ctxObj.receiverLength*14)/2, 90, 86)
  //网点名称
  ctx.fillStyle = '#252525'
  ctx.font = "bold 14px 黑体"
  ctx.fillText(ctxObj.destinationBranchName, 18, 130, 160)
  ctx.drawImage('../../assets/images/index/sharewx1.png', 22+ctxObj.destinationBranchNameLength*14, 117, 48, 16)
  //网点地址
  ctx.fillStyle = '#666'
  ctx.font = "10px 黑体"
  ctx.fillText(ctxObj.destinationAddress, 18, 148, 214)
  //作画
  ctx.draw()


  Taro.canvasToTempFilePath({
    canvasId: 'wxfx',
    success: (res)=>{
      shareData.value.imageUrl = res.tempFilePath
      shareData.value.path = `/pages/receiveAgent/index?billNo=${order.orderList.billNo}&expirationTime=${dayjs((new Date()).getTime() + 24 * 60 * 60 * 1000).format("YYYY-MM-DD HH:mm:ss")}`
      console.log(shareData.value)
      Taro.hideLoading()
      if(resolve){
        resolve(shareData.value)
      }
    }
  })
}

const returnShareData = ()=>{
  Taro.showLoading({
    title: '生成中',
  })
  return new Promise(function(resolve, reject) {
    drawWxShare(resolve)
  })
  //return shareData.value
}

useShareAppMessage(()=>{
  return {
    ...shareData.value,
    promise: returnShareData()
  }
})

// watch(()=>props.show,(val)=>{
//   if(val){
//     drawWxShare()
//   }
// })
</script>

<style lang="scss">
.cs_main {
  width: 100%;
  box-sizing: border-box;
  padding: 0 24rpx 24rpx;
  .times {
    width: 100%;
    height: 104rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #252525;
  }
  .tips {
    width: 100%;
    box-sizing: border-box;
    padding: 20rpx 24rpx;
    border: 1rpx solid #ffd1a3;
    background-color: #ffeddb;
    border-radius: 8rpx;
    color: #ff8f1f;
    .title {
      font-size: 24rpx;
      line-height: 32rpx;
    }
    .content {
      font-size: 20rpx;
      line-height: 28rpx;
      margin-top: 4rpx;
    }
  }
}
.ways {
  width: 100%;
  box-sizing: border-box;
  padding: 32rpx 24rpx;
  border-top: 16rpx solid #f5f5f5;
  .shareBtn {
    margin: 0;
    padding: 0;
    border: none;
    background: transparent;
    &::after {
      border: none;
    }
  }
  .title {
    color: #252525;
    font-size: 28rpx;
    line-height: 40rpx;
  }
  .content {
    width: 100%;
    box-sizing: border-box;
    padding-left: 24rpx;
    margin-top: 32rpx;
    display: flex;
    align-items: center;
    .block {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 48rpx;
      image {
        width: 92rpx;
        height: 92rpx;
      }
      text {
        margin-top: 12rpx;
        font-size: 24rpx;
        line-height: 32rpx;
        color: #999;
      }
    }
  }
}
.wrapper_sms {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  overflow: hidden;
  width: 590rpx;
  height: 400rpx;
  //height: 362rpx;
  border-radius: 20rpx;
  background-color: #fff;
  margin: 50vh auto;
  transform: translateY(-50%);
  box-sizing: border-box;
  padding: 0 32rpx;
  .heads {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 96rpx;
    background: linear-gradient(180deg, #BED5FC -153%, rgba(9,102,255,0.00) 100%);
  }
  .formtitle {
    color: #252525;
    width: 100%;
    text-align: center;
    font-size: 32rpx;
    font-weight: 600;
    margin-top: 32rpx;
  }
  .nut-input {
    width: 526rpx;
    height: 72rpx;
    margin-top: 32rpx;
    border-radius: 8rpx;
    box-sizing: border-box;
    padding: 0 28rpx;
    background-color: #f5f5f5;
    .input-text {
      line-height: 72rpx !important;
      height: 72rpx !important;
    }
    .input-placeholder {
      line-height: 72rpx !important;
    }
  }
  .foots {
    margin-top: 64rpx;
    width: 100%;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    .left_btn {
      box-sizing: border-box;
      width: 208rpx;
      height: 72rpx;
      border-radius: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      letter-spacing: 10rpx;
      background-color: #fff;
      border: 1rpx solid #c4c4c4;
      color: #252525;
    }
    .right_btn {
      box-sizing: border-box;
      width: 208rpx;
      height: 72rpx;
      border-radius: 36rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      letter-spacing: 10rpx;
      background-color: #0966ff;
      color: #fff;
      margin-left: 24rpx;
    }
  }
}

.qrs {
  width: calc(100% - 48rpx);
  overflow: hidden;
  border-radius: 16rpx;
  margin-left: 24rpx;
  margin-bottom: 24rpx;
  border-top: none;
  background-color: #fff;
  .bill_body {
    width: calc(100% - 48rpx);
    box-sizing: border-box;
    border: 1px solid #e3e7ec;
    background-color: #fff;
    margin: 24rpx;
    > .layers {
      width: 100%;
      box-sizing: border-box;
      padding: 0 24rpx;
      border-bottom: 1px solid #e3e7ec;
      display: flex;
      overflow-x: hidden;
      &.f2 {
        flex-wrap: wrap;
        > view {
          width: 100%;
          height: 112rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .img {
            width: 40rpx;
            height: 40rpx;
          }
          .address {
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: calc(100% - 56rpx);
            .name {
              font-weight: bold;
              font-size: 26rpx;
              color: #252525;
            }
            .addr {
              font-weight: 500;
              font-size: 22rpx;
              color: #999;
              margin-top: 18rpx;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              width: 100%
            }
          }
        }
      }
      &.f3 {
        &:last-child {
          border-bottom: none;
        }
        padding-bottom: 24rpx;
        flex-wrap: wrap;
        .row {
          width: 100%;
          margin-top: 24rpx;
          display: flex;
          font-size: 22rpx;
          font-weight: 500;
          .width_100 {
            width: 100%;
            .label {
              width: 152rpx;
              color: #999;
            }
            .value {
              width: calc(100% - 152rpx);
              color: #252525;
            }
          }
          .width_50 {
            width: 50%;
            .label {
              width: 152rpx;
              color: #999;
            }
            .value {
              width: calc(100% - 152rpx);
              color: #252525;
            }
          }
          .sub_info {
            width: 100%;
            border-radius: 8rpx;
            padding: 0 12rpx 12rpx;
            background-color: #f8f9fa;
            >view {
              width: 100%;
              margin-top: 12rpx;
              display: flex;
            }
          }
        }
      }
      &.qr {
        width: 100%;
        height: 192rpx;
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        box-sizing: border-box;
        .img1 {
          width: 72rpx;
          height: 72rpx;
        }
        .text {
          width: 380rpx;
          font-size: 28rpx;
          line-height: 44rpx;
          box-sizing: border-box;
          padding-left: 16rpx;
        }
        .img2 {
          width: 144rpx;
          height: 144rpx;
        }
      }
    }
  }
  .title_qr {
    width: 100%;
    height: 112rpx;
    background-color: #0966ff;
    box-sizing: border-box;
    padding: 0 40rpx 0 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .img {
      width: 208rpx;
      height: 68rpx;
    }
    .right {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .phone {
        width: 32rpx;
        height: 32rpx;
      }
      .text {
        margin-left: 8rpx;
        font-size: 24rpx;
        font-weight: bold;
        color: #fff;
      }
    }
  }
}
.qrfoot {
  width: 100%;
  height: 128rpx;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  .btn {
    width: 700rpx;
    height: 88rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #0966ff;
    color: #fff;
    border-radius: 44rpx;
  }
}
</style>
